/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.toools.gwt.wmc.server.dao.toplink;

import java.util.Collection;
import javax.persistence.NoResultException;
import oracle.toplink.essentials.ejb.cmp3.EntityManager;
import oracle.toplink.essentials.expressions.Expression;
import oracle.toplink.essentials.expressions.ExpressionBuilder;
import org.springframework.stereotype.Repository;
import org.toools.gwt.wmc.server.dao.IWasteDAO;
import org.toools.gwt.wmc.jpa.Waste;

/**
 *
 * @author ich
 */
@Repository
public class WasteDAO implements IWasteDAO{

//    private EntityManager em;
//
//    @PersistenceContext
//    public void setEntityManager( EntityManager em ) {
//        this.em = em;
//    }

    public Waste getWasteByID(Integer id) {
        Waste result;
        try {
            result = (Waste) EMFKeeper.EM.createNamedQuery("Waste.getById").setParameter("id", id).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
        System.out.println("fetched waste " + result.getGtin() + " from db.");
        return result;
    }

    public Boolean belongsTo( Integer id, Integer accountid ) {
        EntityManager em = (EntityManager)EMFKeeper.EM;
        ExpressionBuilder eb = new ExpressionBuilder();
        //company mit zugehörigemm account
        Expression container = eb.get( "id" ).equal( id );
        Expression acc = eb.anyOf("containers").anyOf("companyParts").get( "company" ).get("account").get("id").equal( accountid );
        Expression belongsto = container.and( acc );

        return em.getSession().readAllObjects( Waste.class, belongsto ).size() > 0;
    }

    public Collection<Waste> getWastes() {
        Collection<Waste> ret = EMFKeeper.EM.createNamedQuery("Waste.getAll").getResultList();

        System.out.println("fetched " + ret.size() + " wastes from db.");
        return ret;
    }

    public Collection<Waste> getWastes(Integer accountid) {
        EntityManager em = (EntityManager)EMFKeeper.EM;

        ExpressionBuilder eb = new ExpressionBuilder();
        Expression accadditives = eb.anyOf("containers").anyOf( "companyParts" ).get( "company" ).get( "account" ).get( "id" ).equal( accountid );

        Collection<Waste> ret = em.getSession().readAllObjects( Waste.class, accadditives );
        return ret;
    }

    public Waste create(Waste c) {
        return SimpleCUD.create( c );
    }

    public Boolean delete(Waste c) {
        Waste rem = (Waste)EMFKeeper.EM.createNamedQuery("Waste.getById").setParameter("id", c.getGtin()).getSingleResult();
        return SimpleCUD.delete( rem );
    }

    public Boolean update(Waste c) {
        return SimpleCUD.update( c );
    }
}
